package net.apisp.quick.example.config;

import net.apisp.quick.config.Configuration;
import net.apisp.quick.ioc.annotation.Autowired;
import net.apisp.quick.server.ServerContext;
import net.apisp.quick.server.std.QuickContext;
import net.apisp.quick.template.T;
import net.apisp.quick.util.Strings;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


public class TemplateKit extends T {

    public static TemplateKit newT() {
        return new TemplateKit();
    }

    @Override
    public String render(Path thtml) {
        try {
            QuickContext context = ServerContext.tryGet();
            byte[] file = Files.readAllBytes(thtml);
            String templateStr = new String(file, (String) Configuration.get("charset"));
            Map<String,Object> varMap = Optional.ofNullable(vars).orElse(new HashMap<>());
            org.beetl.core.Configuration config = context.singleton(org.beetl.core.Configuration.class);
            StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
            GroupTemplate groupTemplate = new GroupTemplate(resourceLoader, config);
            Template template = groupTemplate.getTemplate(templateStr);
            template.binding(varMap);
            return template.render();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.vars = null;
        }
        return "";
    }
    @Override
    public byte[] render2bin(Path thtml) {
        try {
            return render(thtml).getBytes((String) Configuration.get("charset"));
        } catch (UnsupportedEncodingException e) {
            return render(thtml).getBytes();
        }
    }
}
